// Copyright (c) 2023 坚果派
// 公众号：nutpi
// 电话：17752170152
// 官网：https://www.nutpi.net/
// All rights reserved.

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/weight_management_provider.dart';
import '../models/weight_record.dart';
import '../utils/bmi_calculator.dart';
import 'package:uuid/uuid.dart';
import 'package:intl/intl.dart';

class WeightManagementPage extends StatefulWidget {
  const WeightManagementPage({Key? key}) : super(key: key);

  @override
  State<WeightManagementPage> createState() => _WeightManagementPageState();
}

class _WeightManagementPageState extends State<WeightManagementPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final _formKey = GlobalKey<FormState>();
  final _weightController = TextEditingController();
  final _waistController = TextEditingController();
  final _notesController = TextEditingController();
  double? _height;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);

    // 加载保存的身高
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final provider =
          Provider.of<WeightManagementProvider>(context, listen: false);
      setState(() {
        _height = provider.height;
      });
    });
  }

  @override
  void dispose() {
    _tabController.dispose();
    _weightController.dispose();
    _waistController.dispose();
    _notesController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title:
            const Text('体重管理年', style: TextStyle(fontWeight: FontWeight.bold)),
        backgroundColor: Theme.of(context).colorScheme.primary,
        foregroundColor: Colors.white,
        bottom: TabBar(
          controller: _tabController,
          indicatorColor: Colors.white,
          tabs: const [
            Tab(icon: Icon(Icons.monitor_weight), text: '体重记录'),
            Tab(icon: Icon(Icons.add_chart), text: '添加记录'),
            Tab(icon: Icon(Icons.info_outline), text: '健康知识'),
          ],
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          _buildWeightRecordsTab(),
          _buildAddRecordTab(),
          _buildHealthKnowledgeTab(),
        ],
      ),
    );
  }

  Widget _buildWeightRecordsTab() {
    return Consumer<WeightManagementProvider>(
      builder: (context, provider, child) {
        final records = provider.weightRecords;

        if (records.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.scale, size: 64, color: Colors.grey[400]),
                const SizedBox(height: 16),
                const Text('暂无体重记录',
                    style: TextStyle(fontSize: 18, color: Colors.grey)),
                const SizedBox(height: 8),
                Text('开始记录您的体重变化吧！',
                    style: TextStyle(fontSize: 14, color: Colors.grey[600])),
                const SizedBox(height: 24),
                ElevatedButton.icon(
                  icon: const Icon(Icons.add),
                  label: const Text('添加记录'),
                  onPressed: () {
                    _tabController.animateTo(1);
                  },
                ),
              ],
            ),
          );
        }

        return ListView.builder(
          padding: const EdgeInsets.all(16),
          itemCount: records.length,
          itemBuilder: (context, index) {
            final record = records[index];
            final bmiCategory = record.bmi != null
                ? BMICalculator.getBMICategory(record.bmi!)
                : '未计算';
            final bmiColor = record.bmi != null
                ? BMICalculator.getBMIColor(record.bmi!)
                : Colors.grey;

            return Card(
              elevation: 2,
              margin: const EdgeInsets.only(bottom: 16),
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          DateFormat('yyyy年MM月dd日').format(record.recordTime),
                          style: const TextStyle(
                              fontWeight: FontWeight.bold, fontSize: 16),
                        ),
                        IconButton(
                          icon: const Icon(Icons.delete_outline,
                              color: Colors.red),
                          onPressed: () => _confirmDelete(context, record.id),
                        ),
                      ],
                    ),
                    const Divider(),
                    const SizedBox(height: 8),
                    Row(
                      children: [
                        Expanded(
                          child: _buildInfoItem(
                            icon: Icons.monitor_weight,
                            label: '体重',
                            value: '${record.weight} kg',
                          ),
                        ),
                        if (record.waistCircumference != null)
                          Expanded(
                            child: _buildInfoItem(
                              icon: Icons.straighten,
                              label: '腰围',
                              value: '${record.waistCircumference} cm',
                            ),
                          ),
                      ],
                    ),
                    const SizedBox(height: 16),
                    Row(
                      children: [
                        if (record.bmi != null)
                          Expanded(
                            child: _buildInfoItem(
                              icon: Icons.speed,
                              label: 'BMI',
                              value: record.bmi!.toStringAsFixed(1),
                              color: bmiColor,
                            ),
                          ),
                        if (record.bodyFatPercentage != null)
                          Expanded(
                            child: _buildInfoItem(
                              icon: Icons.percent,
                              label: '体脂率',
                              value:
                                  '${record.bodyFatPercentage!.toStringAsFixed(1)}%',
                            ),
                          ),
                      ],
                    ),
                    if (record.bmi != null)
                      Padding(
                        padding: const EdgeInsets.only(top: 8),
                        child: Text(
                          '体重状态: $bmiCategory',
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            color: bmiColor,
                          ),
                        ),
                      ),
                    if (record.notes != null && record.notes!.isNotEmpty)
                      Padding(
                        padding: const EdgeInsets.only(top: 16),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            const Text('备注:',
                                style: TextStyle(fontWeight: FontWeight.bold)),
                            const SizedBox(height: 4),
                            Text(record.notes!),
                          ],
                        ),
                      ),
                  ],
                ),
              ),
            );
          },
        );
      },
    );
  }

  Widget _buildInfoItem({
    required IconData icon,
    required String label,
    required String value,
    Color? color,
  }) {
    return Row(
      children: [
        Icon(icon, color: color ?? Theme.of(context).primaryColor, size: 20),
        const SizedBox(width: 8),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(label,
                style: TextStyle(fontSize: 12, color: Colors.grey[600])),
            Text(
              value,
              style: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 16,
                color: color,
              ),
            ),
          ],
        ),
      ],
    );
  }

  Future<void> _confirmDelete(BuildContext context, String id) async {
    return showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除记录'),
        content: const Text('确定要删除这条体重记录吗？此操作不可恢复。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Provider.of<WeightManagementProvider>(context, listen: false)
                  .deleteWeightRecord(id);
              Navigator.of(context).pop();
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('记录已删除')),
              );
            },
            child: const Text('删除', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );
  }

  Widget _buildAddRecordTab() {
    // 确保总是返回一个Widget
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Card(
              elevation: 2,
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      '身高设置',
                      style:
                          TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(height: 8),
                    Consumer<WeightManagementProvider>(
                      builder: (context, provider, child) {
                        return Row(
                          children: [
                            Expanded(
                              child: TextFormField(
                                initialValue: provider.height?.toString() ?? '',
                                decoration: const InputDecoration(
                                  labelText: '身高 (cm)',
                                  border: OutlineInputBorder(),
                                  suffixText: 'cm',
                                ),
                                keyboardType: TextInputType.number,
                                validator: (value) {
                                  if (value == null || value.isEmpty) {
                                    return '请输入身高';
                                  }
                                  final height = double.tryParse(value);
                                  if (height == null ||
                                      height <= 0 ||
                                      height > 300) {
                                    return '请输入有效的身高';
                                  }
                                  return null;
                                },
                                onChanged: (value) {
                                  final height = double.tryParse(value);
                                  if (height != null && height > 0) {
                                    provider.setHeight(height);
                                  }
                                },
                              ),
                            ),
                            const SizedBox(width: 16),
                            ElevatedButton(
                              onPressed: () {
                                if (_formKey.currentState!.validate()) {
                                  ScaffoldMessenger.of(context).showSnackBar(
                                    const SnackBar(content: Text('身高已保存')),
                                  );
                                }
                              },
                              child: const Text('保存'),
                            ),
                          ],
                        );
                      },
                    ),
                    const SizedBox(height: 16),
                    const Text('您的身高数据将用于计算BMI值，帮助您更好地管理体重。'),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 24),
            const Text(
              '添加体重记录',
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),
            TextFormField(
              controller: _weightController,
              decoration: const InputDecoration(
                labelText: '体重 (kg)',
                border: OutlineInputBorder(),
                prefixIcon: Icon(Icons.monitor_weight),
                suffixText: 'kg',
              ),
              keyboardType: TextInputType.number,
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入体重';
                }
                final weight = double.tryParse(value);
                if (weight == null || weight <= 0 || weight > 500) {
                  return '请输入有效的体重';
                }
                return null;
              },
            ),
            const SizedBox(height: 16),
            TextFormField(
              controller: _waistController,
              decoration: const InputDecoration(
                labelText: '腰围 (cm, 选填)',
                border: OutlineInputBorder(),
                prefixIcon: Icon(Icons.straighten),
                suffixText: 'cm',
              ),
              keyboardType: TextInputType.number,
              validator: (value) {
                if (value != null && value.isNotEmpty) {
                  final waist = double.tryParse(value);
                  if (waist == null || waist <= 0 || waist > 300) {
                    return '请输入有效的腰围';
                  }
                }
                return null;
              },
            ),
            const SizedBox(height: 16),
            TextFormField(
              controller: _notesController,
              decoration: const InputDecoration(
                labelText: '备注 (选填)',
                border: OutlineInputBorder(),
                prefixIcon: Icon(Icons.note),
              ),
              maxLines: 3,
            ),
            const SizedBox(height: 24),
            SizedBox(
              width: double.infinity,
              child: ElevatedButton.icon(
                icon: const Icon(Icons.save),
                label: const Text('保存记录'),
                style: ElevatedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(vertical: 16),
                ),
                onPressed: _saveRecord,
              ),
            ),
            const SizedBox(height: 24),
            const Text(
              '体重管理贴士:',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 8),
            const Card(
              child: Padding(
                padding: EdgeInsets.all(16),
                child: Column(
                  children: [
                    ListTile(
                      leading:
                          Icon(Icons.lightbulb_outline, color: Colors.amber),
                      title: Text('定期测量'),
                      subtitle: Text('每天同一时间测量体重，保持记录一致性'),
                    ),
                    Divider(),
                    ListTile(
                      leading: Icon(Icons.restaurant, color: Colors.green),
                      title: Text('均衡饮食'),
                      subtitle: Text('践行"三减三健"：减油、减盐、减糖，健康口腔、健康体重、健康骨骼'),
                    ),
                    Divider(),
                    ListTile(
                      leading: Icon(Icons.directions_run, color: Colors.blue),
                      title: Text('适量运动'),
                      subtitle: Text('每周至少150分钟中等强度有氧运动'),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _saveRecord() {
    if (_formKey.currentState!.validate()) {
      final weight = double.parse(_weightController.text);
      final waist = _waistController.text.isNotEmpty
          ? double.parse(_waistController.text)
          : null;
      final notes =
          _notesController.text.isNotEmpty ? _notesController.text : null;

      final provider =
          Provider.of<WeightManagementProvider>(context, listen: false);

      // 计算BMI (如果有身高数据)
      double? bmi;
      if (provider.height != null) {
        bmi = BMICalculator.calculateBMI(weight, provider.height!);
      }

      final record = WeightRecord(
        id: const Uuid().v4(),
        weight: weight,
        waistCircumference: waist,
        bmi: bmi,
        bodyFatPercentage: null, // 可以后续添加计算方法
        recordTime: DateTime.now(),
        notes: notes,
      );

      provider.addWeightRecord(record);

      // 清空表单
      _weightController.clear();
      _waistController.clear();
      _notesController.clear();

      // 显示成功消息
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('体重记录已保存')),
      );

      // 切换到记录tab
      _tabController.animateTo(0);
    }
  }

  Widget _buildHealthKnowledgeTab() {
    // 确保总是返回一个Widget
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '"体重管理年"活动简介',
            style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 8),
          const Card(
            child: Padding(
              padding: EdgeInsets.all(16),
              child: Text(
                '体重水平与人体健康状况密切相关，体重异常特别是超重和肥胖是导致心脑血管疾病、糖尿病和部分癌症等慢性病的重要危险因素。为贯彻党中央决策部署，落实《健康中国行动（2019-2030年）》有关工作要求，倡导和推进文明健康生活方式，启动实施"体重管理年"活动。',
                style: TextStyle(fontSize: 15),
              ),
            ),
          ),
          const SizedBox(height: 16),
          const Text(
            '健康体重标准',
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 8),
          _buildBMITable(),
          const SizedBox(height: 16),
          const Text(
            '"三知一管"理念',
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 8),
          Card(
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                children: [
                  _buildKnowledgeItem(
                    '知晓健康体重标准',
                    '了解BMI指数、腰围等健康体重的评价标准',
                    Icons.scale,
                    Colors.blue,
                  ),
                  const Divider(),
                  _buildKnowledgeItem(
                    '知晓自身体重变化',
                    '定期测量体重、腰围，了解自身体重变化趋势',
                    Icons.trending_up,
                    Colors.orange,
                  ),
                  const Divider(),
                  _buildKnowledgeItem(
                    '知晓体重管理方法',
                    '掌握合理膳食、适量运动等健康生活方式',
                    Icons.lightbulb_outline,
                    Colors.green,
                  ),
                  const Divider(),
                  _buildKnowledgeItem(
                    '科学管理自身体重',
                    '综合运用各种方法，保持健康体重',
                    Icons.health_and_safety,
                    Colors.purple,
                  ),
                ],
              ),
            ),
          ),
          const SizedBox(height: 16),
          const Text(
            '吃动平衡原则',
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 8),
          Card(
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                children: [
                  Image.asset(
                    'assets/images/balance_diet.png',
                    height: 150,
                    fit: BoxFit.contain,
                    errorBuilder: (context, error, stackTrace) => Container(
                      height: 150,
                      color: Colors.grey[200],
                      child: const Center(
                        child: Icon(Icons.image_not_supported, size: 50),
                      ),
                    ),
                  ),
                  const SizedBox(height: 16),
                  const Text(
                    '体重管理的核心是能量平衡：摄入的能量应与消耗的能量相匹配。'
                    '控制饮食（减少高热量、高脂肪、高糖食物摄入）和增加身体活动（每天至少30分钟中等强度运动）是维持健康体重的关键。',
                    style: TextStyle(fontSize: 15),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBMITable() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Table(
          border: TableBorder.all(color: Colors.grey[300]!),
          columnWidths: const {
            0: FlexColumnWidth(2),
            1: FlexColumnWidth(3),
            2: FlexColumnWidth(2),
          },
          children: [
            TableRow(
              decoration: BoxDecoration(color: Colors.grey[200]),
              children: [
                _buildTableCell('BMI范围', isHeader: true),
                _buildTableCell('分类', isHeader: true),
                _buildTableCell('风险', isHeader: true),
              ],
            ),
            TableRow(
              children: [
                _buildTableCell('<18.5'),
                _buildTableCell('偏瘦'),
                _buildTableCell('低', textColor: Colors.blue),
              ],
            ),
            TableRow(
              children: [
                _buildTableCell('18.5-23.9'),
                _buildTableCell('正常'),
                _buildTableCell('平均', textColor: Colors.green),
              ],
            ),
            TableRow(
              children: [
                _buildTableCell('24.0-27.9'),
                _buildTableCell('超重'),
                _buildTableCell('增加', textColor: Colors.orange),
              ],
            ),
            TableRow(
              children: [
                _buildTableCell('≥28.0'),
                _buildTableCell('肥胖'),
                _buildTableCell('高', textColor: Colors.red),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTableCell(String text,
      {bool isHeader = false, Color? textColor}) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Text(
        text,
        textAlign: TextAlign.center,
        style: TextStyle(
          fontWeight: isHeader ? FontWeight.bold : FontWeight.normal,
          color: textColor,
        ),
      ),
    );
  }

  Widget _buildKnowledgeItem(
      String title, String description, IconData icon, Color color) {
    return ListTile(
      leading: CircleAvatar(
        backgroundColor: color.withOpacity(0.2),
        child: Icon(icon, color: color),
      ),
      title: Text(title, style: const TextStyle(fontWeight: FontWeight.bold)),
      subtitle: Text(description),
    );
  }
}
